//  计划
var express = require("express");
var router = express.Router();
var planLists = require("./../models/planList");
var clubs = require("./../models/club");
var multer = require("multer");
let fs = require("fs");
let path = require("path");
var moment = require('moment');

function returnRes(obj) {
  const { res, code, data, message } = obj
  res.json({
    code: code,
    data: data ? data : null,
    message: message ? message : '成功' //失败的情况下，需要传入失败信息 否则默认成功
  });
  return false
}
// 格式化天
function formatMyDay(d) {
  return d < 10 ? "0" + d : d;
}
// 获取每年下的月数据和周数据
function getMonthList(item) {
  // 获取月份的开始和结束值
  let startM = Number(item.timeArea[0].slice(5, 7));
  let endM = Number(item.timeArea[1].slice(5, 7));
  let monthList = []
  // 遍历每一年的月份，算出月初和月末，当前月需要特殊处理，因为它可能是从月中开始的。
  for (let i = startM, s = -1; i <= endM; i++) {
    let monthObj = {}
    s++;
    let value; //每月月初日期
    // 获取月初时间,当前月的月初时间为当天
    if (s === 0) {
      value =
        item.yearNum +
        "-" +
        moment(item.timeArea[0]).add(s, "M").format("MM-DD");
    } else {
      //   获取月初
      value =
        item.yearNum +
        "-" +
        moment(item.timeArea[0])
          .add(s, "M")
          .startOf("Month")
          .format("MM-DD");
    }
    let monthS = Number(value.slice(8, 10)) //月初
    let monthE = Number(
      moment(value).endOf("Month").format("YYYY-MM-DD").slice(8, 10)
    ) //月末
    let weekList = [] //月区间的周列表
    // 处理周数据----start
    let ss = parseInt((monthE - monthS) / 7); //取商
    let sm = (monthE - monthS) % 7; //取余数
    for (let iw = 0; iw < ss; iw++) {
      let weekS = value.slice(0, 8) + formatMyDay(monthS + iw * 7)
      let weekE =
        value.slice(0, 8) +
        formatMyDay(monthS + iw * 7 + (iw == ss - 1 ? 7 + sm : 6));
      let weekObj = {
        planType: 'week',
        planTypeText: '周计划',
        timeArea: [weekS, weekE],
        title: item.yearNum + '年' + i + '月' + '第' + (iw + 1) + '周',
        weekNum: iw + 1,
        status: 0,
        contentList: [{
          index: 0,
          title: "",
          text: "",
        }]
      };
      weekList.push(weekObj);

    }
    // 处理周数据----end

    monthObj = {
      planTypeText: "月度计划", //计划周期文字
      title: item.yearNum + '年' + i + "月",
      planType: "month",
      yearNum: item.yearNum, //当前选中的年份
      monthNum: i, //当前选中的月份
      timeArea: [value, moment(value).endOf("Month").format("YYYY-MM-DD")],
      status: 0,
      contentList: [
        //计划内容
        {
          index: 0,
          title: "",
          text: "",
        },
      ],
      children: weekList,
    }
    monthList.push(monthObj)
  }
  return monthList
}

// 新增
router.post("/addPlan", function (req, res, next) {
  let { planType, planTypeText, timeArea, title, yearNum, monthNum, weekNum } = data = req.body;
  planLists.findOne(function (err1, doc1) {
    const initCollection = {
      yearFive: [],
      year: [
        // {
        //   planType: '',
        //   planTypeText: '',
        //   timeArea: [],
        //   title: '年',
        //   yearNum: null,
        //   contentList: [],
        //   children: [{
        //     planType: '',
        //     planTypeText: '',
        //     timeArea: [],
        //     title: '月',
        //     monthNum: null,
        //     contentList: [],
        //     children: [{
        //       planType: '',
        //       planTypeText: '',
        //       timeArea: [],
        //       title: '周',
        //       weekNum: null,
        //       contentList: [],
        //     }],
        //   }]

        // }
      ]
    }
    //【逻辑1】
    // 集合不存在，新建集合
    if (doc1 == "" || doc1 == null) {
      // 这里加个判断，如果集合为空，但是，此时添加又不是5年计划，需要给出提示：请先设置5年计划
      if (planType !== 'yearFive') {
        returnRes({ res, code: -1, message: '请先设置5年计划！再设置其它区间计划！' })
        return false
      }
      // 创建集合，给5年集合赋值，初始化年月日数据
      initCollection.yearFive[0] = data
      // 5年期初始化时间
      let yearFiveStart = timeArea[0].slice(0, 4) - 0
      // 5年期结束时间
      let yearFiveEnd = timeArea[1].slice(0, 4) - 0
      let yearArr = [], //年数据，只存年份值
        yearList = []//存储年份值下面的数据
      for (let i = 0; i <= yearFiveEnd - yearFiveStart; i++) {
        yearArr.push(i + 1)
      }
      // 通过5年期的时间段，来创建年数据
      yearArr.forEach((item, index) => {
        // 如果是当前年只需要当前日期到当年结束日期
        let yearS, //每年开始时间
          yearE //每年结束时间
        if (!index) {//第一年时间只要计算到当前时间到当年结束时间，月，周同理
          yearS = timeArea[0];
          yearE = moment(yearFiveStart + "")
            .endOf("Year")
            .format("YYYY-MM-DD");
        } else {
          // 否则，某年完整的开始时间和结束时间
          yearS = moment(yearFiveStart + index + "")
            .startOf("Year")
            .format("YYYY-MM-DD");
          yearE = moment(yearFiveStart + index + "")
            .endOf("Year")
            .format("YYYY-MM-DD");
        }
        yearList.push({
          planTypeText: "年度计划", //计划周期文字
          title: yearS.slice(0, 4) + "年度计划", //计划标题
          planType: "year",
          timeArea: [yearS, yearE],
          yearNum: yearS.slice(0, 4), //当前选中的年份
          monthNum: "", //当前选中的月份
          status: 0,
          contentList: [
            //计划内容
            {
              index: 0,
              title: "",
              text: "",
            },
          ],
          children: []

        });

      });
      // 通过每年的时间段。来创建月数据
      yearList.forEach((item, index) => {
        item.children = getMonthList(item)
      })


      // 赋值年份下的完整数据
      initCollection.year = yearList

      planLists.create(initCollection, function (err, doc) {
        if (err) {
          returnRes({ res, code: -1, message: err })
        } else {
          returnRes({ res, code: 0, message: '集合创建成功' })
        }
      });
    } else {
      /**【逻辑2】
       * 增加各个区间的数据
       */
      // 如果添加的数据已经存在，就要提示
      let returnFlag = true
      // 根据类型来判断
      switch (planType) {
        case 'yearFive':
          if (doc1[data.planType][0]?.title) {
            returnFlag = fasle
            returnRes({ res, code: -1, message: '当前区间计划已经存在了！您可以尝试修改，或者制定其它区间的计划！' })
          }
          if (!returnFlag) {
            return false
          }




          break;
        case 'year':
          doc1[planType].forEach((item, index) => {
            if (item.yearNum == yearNum) {
              returnFlag = fasle
              returnRes({ res, code: -1, message: '当前区间计划已经存在了！您可以尝试修改，或者制定其它区间的计划！' })
            }
          })

          if (!returnFlag) {
            return false
          }
          doc1[planType].push(data)
          break;
        case 'month':
          doc1.year.forEach((item, index) => {
            if (item.yearNum == yearNum) {
              item.children.forEach((item1, index1) => {
                if (item1.monthNum == monthNum) {
                  returnFlag = fasle
                  returnRes({ res, code: -1, message: '当前区间计划已经存在了！您可以尝试修改，或者制定其它区间的计划！' })

                }
              })
              doc1.year[index].children.push(data)
            }
          })
          if (!returnFlag) {
            return false
          }
          break;
        case 'week':
          let flagMonth
          doc1.year.forEach((item, index) => {
            if (item.yearNum == yearNum) {
              item.children.forEach((item1, index1) => {
                if (item1.monthNum == monthNum) {
                  flagMonth = index1
                  item1.children.forEach((item2, index2) => {
                    if (item2.weekNum == weekNum) {
                      returnFlag = fasle
                      returnRes({ res, code: -1, message: '当前区间计划已经存在了！您可以尝试修改，或者制定其它区间的计划！' })
                    }
                  })

                }
              })

            }
            doc1.year[index].children[flagMonth].children.push(data)
          })
          if (!returnFlag) {

            return false
          }
          break;

        default:
          break;
      }

      doc1.save(function (err2, doc2) {
        if (err2) {
          returnRes({ res, code: -1, message: err2 })
        } else {
          returnRes({ res, code: 0, message: '添加成功' })
        }
      })
    }
  });
});


// 删除分类
router.post("/delete", function (req, res, next) {
  let { id, childId } = req.body;
  let wherestr = {
    id: 1,
  };
  planLists.remove(wherestr, function (err, doc) {
    doc.article[types].forEach((item, index) => {
      if (item.id == id) {
        doc.article[types].splice(index, 1);

        doc.save(function (err1, doc1) {
          if (err1) {
            res.json({
              status: "1",
              msg: "删除失败" + err1,
            });
          } else {
            res.json({
              status: "0",
              msg: "删除成功",
            });
          }
        });
      }
    });
  });
});

// 获取年月日区间计划表
/**
 * planType：周期类型，必传
 * yearNum, monthNum, weekNum 年月日对应的时间值
 * yearNum, monthNum, weekNum 年月日对应的时间值
 * isDeleteChild 是否删除子节点，即查询2022年的时候只返回2022年的数据，不返回2022年下的月度和周数据
 */
router.post("/pageList", function (req, res, next) {
  let { planType, yearNum, monthNum, weekNum, isDeleteChild } = data = req.body;
  planLists.findOne(function (err, doc) {
    doc = doc.toObject() // 修改这里就可以，将doc转换为Object对象
    if (err) {
      returnRes({ res, code: -1, message: err })
      return false
    }
    // 根据类型来判断
    let yearData, monthData, weekData
    switch (planType) {
      case 'yearFive':
        returnRes({ res, code: 0, data: !doc ? null : doc[planType][0], message: '成功' })
        break;
      case 'year':
        // 年度计划
        yearData = doc[planType].filter(item => item.yearNum == yearNum) || []
        // 当查询当前周期的计划时，是不需要返其它周期的数据，否则很卡顿

        yearData = yearData[0]

        // 如果没有传年份，那么直接把所有年的数据都返回
        if (!yearNum) {
          yearData = doc[planType]
          yearData.forEach(item => {
            if (isDeleteChild) {
              item.children = []
            }

          })
        } else {
          if (isDeleteChild) {
            yearData.children = []
          }
        }

        returnRes({ res, code: 0, data: !doc ? null : yearData, message: '成功' })
        break;
      case 'month':
        // 月度计划
        yearData = doc.year.filter(item => item.yearNum == yearNum) || []
        yearData = yearData[0]

        if (yearData?.children) {
          yearData.children.forEach((item, index) => {
            if (item.monthNum == monthNum) {
              monthData = item
            }
          })
        }
        if (isDeleteChild) {
          monthData.children = []
        }
        returnRes({ res, code: 0, data: !doc ? null : monthData, message: '成功' })
        break;
      case 'week':
        // 周度计划
        yearData = doc.year.filter(item => item.yearNum == yearNum) || []
        yearData = yearData[0]
        if (yearData?.children) {
          yearData.children.forEach((item, index) => {
            if (item.monthNum == monthNum) {
              // 没有传周值，就返回月份下的周
              if (!weekNum) {
                weekData = item.children
              } else {

                item.children.forEach((item1, index1) => {
                  if (item1.weekNum == weekNum) {
                    weekData = item1
                  }
                })
              }

            }
          })
        }
        // 给周数据添加timeNumber
        /**
         * 这里有个坑，知道mongoose查询出来的对象是document对象，并不是普通的javascript对象，
         * 所以设置list属性并未生效。将document对象转换为普通的javascript对象，
         * 我们可以使用mongoose的Document.prototype.toObject()方法进项转换。修改代码如下：
         * 经过先把document对象转换为普通javascript对象之后，我们就可以使用js object的方法去设置新属了。
         * 即上面的：doc = doc.toObject()
         *  */
        if (Array.isArray(weekData)) {
          for (var i = 0; i < weekData.length; i++) {
            weekData[i].timeNumber = i + 1
          }

        }
        returnRes({ res, code: 0, data: !doc ? null : weekData, message: '成功' })
        break;
      default:
        break;
    }
  });
});
// 获取首页最新计划表
router.post("/homePlanlist", function (req, res, next) {
  planLists.findOne(function (err, doc) {
    if (err) {
      returnRes({ res, code: -1, message: err })
      return false
    }
    let yearData, monthData, weekData = [], returnArr = []
    let currentDate = moment().format('YYYY-MM-DD')
    let yearNum = currentDate.slice(0, 4) - 0 //年份
    let monthNum = currentDate.slice(5, 7) - 0//月份
    let weekNum = Math.ceil(currentDate.slice(5, 7) - 0) //周份
    yearData = doc.year.filter(item => item.yearNum == yearNum) || []
    yearData = yearData[0]

    // 插入5年数据
    returnArr.push({
      name: '5年计划',
      planType: 'yearFive',
      noList: [{
        planType: 'yearFive',
        planTypeText: doc.yearFive[0].planTypeText,
        timeArea: doc.yearFive[0].timeArea,
        title: doc.yearFive[0].title,
        contentList: doc.yearFive[0].contentList
      }]
    })
    // 插入年度数据
    const { planType, planTypeText, timeArea, title, contentList } = yearData
    returnArr.push({
      name: '年度计划',
      planType: planType,
      timeNumber: Number(timeArea[0].slice(0, 4)),
      noList: [{
        planType,
        planTypeText,
        timeArea,
        title,
        contentList
      }]
    })
    // 插入月数据
    if (yearData.children) {
      yearData.children.forEach((item, index) => {
        if (item.monthNum == monthNum) {
          monthData = item
        }
      })
    }
    returnArr.push({
      name: '月度计划',
      planType: monthData.planType,
      timeNumber: Number(monthData.timeArea[0].slice(5, 7)),
      noList: [{
        planType: monthData.planType,
        planTypeText: monthData.planTypeText,
        timeArea: monthData.timeArea,
        title: monthData.title,
        contentList: monthData.contentList,
      }]
    })
    // 插入周数据
    monthData.children.forEach((item, index) => {
      weekData.push({
        planType: item.planType,
        planTypeText: item.planTypeText,
        timeArea: item.timeArea,
        title: item.title,
        contentList: item.contentList,
      })
    })
    returnArr.push({
      name: '周度计划',
      planType: 'week',
      noList: weekData
    })

    returnRes({ res, code: 0, data: !doc ? null : returnArr.reverse(), message: '成功' })
  });
});

// 修改
router.post("/changePlan", function (req, res, next) {
  let { planType, planTypeText, timeArea, title, yearNum, monthNum, weekNum } = data = req.body;
  planLists.findOne(function (err1, doc1) {
    /**【逻辑1】
     * 修改各个区间的数据
     */
    // 根据类型来判断
    if (err1) {
      returnRes({ res, code: -1, message: err1 })
      return false
    }
    switch (planType) {
      case 'yearFive':
        doc1.yearFive = [data]
        break;
      case 'year':
        doc1[planType].forEach((item, index) => {
          if (item.yearNum == yearNum) {
            doc1.year[index].title = data.title
            doc1.year[index].contentList = data.contentList
          }
        })
        break;
      case 'month':
        doc1.year.forEach((item, index) => {
          if (item.yearNum == yearNum) {
            item.children.forEach((item1, index1) => {
              if (item1.monthNum == monthNum) {
                doc1.year[index].children[index1].title = data.title
                doc1.year[index].children[index1].contentList = data.contentList
              }
            })
          }
        })
        break;
      case 'week':

        doc1.year.forEach((item, index) => {
          if (item.yearNum == yearNum) {
            item.children.forEach((item1, index1) => {
              if (item1.monthNum == monthNum) {

                item1.children.forEach((item2, index2) => {
                  if (item2.weekNum == weekNum) {
                    doc1.year[index].children[index1].children[index2].title = data.title
                    doc1.year[index].children[index1].children[index2].contentList = data.contentList
                  }
                })

              }
            })

          }

        })
        break;

      default:
        break;
    }


    doc1.save(function (err2, doc2) {
      if (err2) {
        returnRes({ res, code: -1, message: err2 })
      } else {
        returnRes({ res, code: 0, message: '修改成功' })
      }
    })

  });
});

module.exports = router;
